package com.vito.act.tool

import groovy.json.JsonSlurper
import javax.script.Compilable
import javax.script.CompiledScript
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.SimpleScriptContext

import com.vito.base.util.MD5Util;

class ScriptTool extends ScriptToolInterface {
	public void runClass(String codes){
		GroovyClassLoader groovyCl = new GroovyClassLoader();
		Class groovy = groovyCl.parseClass(codes);
		groovy.newInstance().run();
	}
	public Object runCode(String codes,Map<?, ?> context){
		if(codes==null||codes==""){
			return null;
		}
		CompiledScript script = getCompiledScript(codes);
		ScriptContext scriptContext = new SimpleScriptContext();
		if(context!=null){
			context.each {key,val->
				scriptContext.setAttribute(key,
						val, ScriptContext.ENGINE_SCOPE);
			}
		}
		def obj =script.eval(scriptContext);
		return  obj;
	}
	public Object runCode(String codes){
		if(codes==null||codes==""){
			return null;
		}
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("groovy");
		def obj =engine.eval(codes);
		return  obj;
	}
	private static def scriptObjct=[:];
	private static getCompiledScript(codes){
		def key =MD5Util.MD5(codes);
		def CompiledScript script=scriptObjct."${key}";
		if(script==null){
			ScriptEngineManager manager = new ScriptEngineManager();
			Compilable engine = manager.getEngineByName("groovy");
			script = engine.compile(codes);
			if(script!=null){
				scriptObjct."${key}"=script;
			}
		}
		return script;
	}
	private Map<String,?> parseString2Json(json){
		def root = new JsonSlurper().parseText(json);
		assert root instanceof Map;
		return root;
	}
	public Map<String,?> runActivitiParam(String json,String type,Map<?, ?> context){
		def root = parseString2Json(json);
		if("script"==type){
			return runCode(root.script,context);
		}else if("param"==type){
			def res =[:];
			def map = root.param;
			map.each {key,val->
				res."${key}"=runCode(val,context);
			}
			return res;
		}
	}
	static void main(args){
		ScriptTool s = new ScriptTool();
		//		def list=[1,2,3,4];
		//		def context = [test:list];
		//		String json = "{\"param\":{\"num\":\"int x=0;for(int i=0;i<test.size();i++){x+=test.get(i);};return x;\"}}";
		//		println s.runActivitiParam(json,"param",context);
		println s.runCode("'sss'=='sss'");
	}
}

